package cn.dyn.funchat.netty.server.handler;

import cn.dyn.funchat.utils.TraceIdUtil;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * netty websocket心跳检测处理器
 */
@Slf4j
public class HeartbeatHandler extends ChannelDuplexHandler {
    /**
     * userEventTriggered 用户事件触发
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        TraceIdUtil.putTraceId();
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) evt;
            log.info("心跳超时用户事件触发");
            // 如果是读超时
            IdleState state = event.state();
            if (state == IdleState.READER_IDLE) {
                log.info("读超时");
                ctx.close();
            }
            // 写入超时
            else if (state == IdleState.WRITER_IDLE) {
                log.info("写超时");
                ctx.close();
            }
        }
    }
}
